from fastapi import APIRouter, WebSocket, WebSocketDisconnect, HTTPException
from app.services.asr_service import asr_service
from app.utils.logger import setup_logger
from app.config import settings  # 导入配置实例

logger = setup_logger("asr_router")

# 创建路由器
router = APIRouter(
    prefix="/asr",
    tags=["ASR"],
    responses={404: {"description": "Not found"}},
)

@router.websocket("/ws")
async def asr_endpoint(websocket: WebSocket):
    # 获取 API Key
    api_key = websocket.query_params.get("api_key")
    if api_key != settings.API_KEY:
        await websocket.close(code=1008, reason="Invalid API Key")
        return

    await websocket.accept()
    logger.info("新的 ASR 连接已建立")
    
    # 收集音频数据
    audio_chunks = []
    
    try:
        while True:
            # 接收客户端数据
            data = await websocket.receive()
            
            
            if "text" in data and data["text"] == "end":
                # 客户端发送结束信号
                logger.info("接收到语音结束信号")
                
                # 发送处理中的状态
                await websocket.send_json({
                    "type": "result",
                    "text": ""
                })
                
                if not audio_chunks:
                    await websocket.send_json({
                        "type": "error",
                        "text": "未接收到音频数据"
                    })
                    continue
                
                # 处理收集到的音频数据
                audio_data = b''.join(audio_chunks)
                result = await asr_service.process_audio(audio_data)
                
                # 发送结果
                await websocket.send_json(result)
                
                # 重置音频数据
                audio_chunks = []
            
            elif "bytes" in data:
                # 接收到音频数据
                audio_chunk = data["bytes"]
                audio_chunks.append(audio_chunk)
                
                # 如果积累了一定量的音频数据，发送进度更新
                if len(audio_chunks) % 10 == 0:
                    await websocket.send_json({
                        "type": "result",
                        "text": ""
                    })
    
    except WebSocketDisconnect:
        logger.info("客户端断开连接")
    except Exception as e:
        logger.error(f"WebSocket 出错: {str(e)}")